package core

import (
	"encoding/binary"
	"fmt"
	"net"
	"os"
	"strconv"
	_ "time"
)

type SocketServer struct {
}

func (*SocketServer) Start() {
	service := ":7777"
	tcpAddr, err := net.ResolveTCPAddr("tcp4", service)
	checkError(err)
	listener, err := net.ListenTCP("tcp", tcpAddr)
	checkError(err)

	for {

		conn, err := listener.Accept()
		if err != nil {
			continue
		}
		println("connected:" + strconv.Itoa(len(service)))
		goProcess(conn)

	}

}
func goProcess(conn net.Conn) {
	times := 100000
	// daytime := time.Now().String()

	str := "fucked from godcongs server:2016-09-21 09:20:31.3852023 +0800 CSTfucked" +
		" from godcongs server:2016-09-21 09:20:31.3852023 +0800 CST"

		// "fucked from godcong's server:" + daytime +
		// "fucked from godcong's server:" + daytime +
		// "fucked from godcong's server:" + daytime +
		// "fucked from godcong's server:" + daytime +
		// "fucked from godcong's server:" + daytime +
		// "fucked from godcong's server:" + daytime +
		// "fucked from godcong's server:" + daytime +
		// "fucked from godcong's server:" + daytime +
		// "fucked from godcong's server:" + daytime +
		// "fucked from godcong's server:" + daytime +
		// "fucked from godcong's server:" + daytime +
		// "fucked from godcong's server:" + daytime +
		// "fucked from godcong's server:" + daytime +
		// "fucked from godcong's server:" + daytime +
		// "fucked from godcong's server:" + daytime +
		// "fucked from godcong's server:" + daytime +
		// "fucked from godcong's server:" + daytime +
		// "fucked from godcong's server:" + daytime +
		// "fucked from godcong's server:" + daytime +
		// "fucked from godcong's server:" + daytime +
		// "fucked from godcong's server:" + daytime +
		// "fucked from godcong's server:" + daytime +
		// "fucked from godcong's server:" + daytime

	// strSize := strconv.Itoa(len(str))
	for times > 0 {
		conn.Write([]byte(Int32ToBytes(int32(len(str))))) // don't care about return value

		conn.Write([]byte(str)) // don't care about return value
		times -= 1
	}
	// we're finished with this client
	conn.Close()
}

func checkError(err error) {
	if err != nil {
		fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
		os.Exit(1)
	}
}

func Int32ToBytes(i int32) []byte {
	var buf = make([]byte, 4)
	binary.BigEndian.PutUint32(buf, uint32(i))
	return buf
}
